﻿using System;
using System.Collections.Generic;
using System.Text;
using RayD.Repository.Entites.SystemModule;
using RayD.Core;
using RayD.Repository;
using Dapper;
using System.Data;
using System.Linq;
using RayD.Repository.Core;

namespace RayD.App.SystemModule
{
    public class DataItemApp
    {

        #region 构造函数注入
        private IRepository BaseRepository;
        public DataItemApp(IRepository repository)
        {
            this.BaseRepository = repository;
        }
        #endregion

        #region 获取数据字典
        /// <summary>
        /// 获取列表数据（表体）-- 根据分类编码
        /// </summary>
        /// <returns></returns>
        [Caching]
        public virtual List<DataItemDetailEntity> GetDetailListByCode(string B_ItemCode)
        {
            StringBuilder strSql = new StringBuilder(200);
            strSql.Append(@"Select BASE_DATAITEMDETAIL.B_ItemDetailId
           ,BASE_DATAITEMDETAIL.B_ItemId
           ,BASE_DATAITEMDETAIL.B_ParentId
                        ,BASE_DATAITEMHEAD.B_ItemCode
           ,BASE_DATAITEMDETAIL.B_ItemName
           ,BASE_DATAITEMDETAIL.B_ItemValue
           ,BASE_DATAITEMDETAIL.B_SimpleSpelling
           ,BASE_DATAITEMDETAIL.B_SortCode
           ,BASE_DATAITEMDETAIL.B_EnabledMark
           ,BASE_DATAITEMDETAIL.B_Description
           ,BASE_DATAITEMDETAIL.B_CreateDate
           ,BASE_DATAITEMDETAIL.B_CreateUserId
           ,BASE_DATAITEMDETAIL.B_CreateUserName
           ,BASE_DATAITEMDETAIL.B_ModifyDate
           ,BASE_DATAITEMDETAIL.B_ModifyUserId
           ,BASE_DATAITEMDETAIL.B_ModifyUserName
             FROM BASE_DATAITEMDETAIL  
             LEFT JOIN BASE_DATAITEMHEAD
             ON ( BASE_DATAITEMDETAIL.B_ItemId = BASE_DATAITEMHEAD.B_ItemId )
            WHERE 1=1
            AND BASE_DATAITEMDETAIL.B_EnabledMark = 1
");

            // 虚拟参数
            var dp = new DynamicParameters(new { });
            if (!B_ItemCode.IsEmpty())
            {
                dp.Add("B_ItemCode", B_ItemCode, DbType.String);
                strSql.Append(" And BASE_DATAITEMHEAD.B_ItemCode = @B_ItemCode ");
            }
            strSql.Append(" Order By BASE_DATAITEMDETAIL.B_SortCode ");

            return BaseRepository.FindList<DataItemDetailEntity>(strSql.ToString(), dp).ToList();
        }
        #endregion

        #region 获取数据 - 字典分类
        /// <summary>
        /// 获取树型列表数据
        /// </summary>
        /// <param name="queryJson">查询条件</param>
        /// <returns></returns>
        [Caching]
        public virtual List<DataItemHeadEntity> GetHeadTreeList(string queryJson)
        {
            var expression = LinqExtensions.True<DataItemHeadEntity>();
            var queryParam = queryJson.ToJObject();
            return this.BaseRepository
                .IQueryable(expression)
                .OrderBy(c => c.B_SortCode)
                .ToTree()
                .ToList();
        }
        #endregion

        #region 获取数据 - 字典明细
        /// <summary>
        /// 获取分页列表数据
        /// </summary>
        /// <param name="queryJson">查询条件</param>
        /// <param name="pagination">分页参数</param>
        /// <returns></returns>
        public IEnumerable<DataItemDetailEntity> GetDetailPageList(string queryJson, Pagination pagination)
        {
            var expression = LinqExtensions.True<DataItemDetailEntity>();
            var queryParam = queryJson.ToJObject();
            if (!queryParam["B_ItemId"].IsEmpty())
            {
                expression = expression.And(c => c.B_ItemId == queryParam["B_ItemId"].ToString());
            }
            var list = this.BaseRepository.IQueryable(expression)
                        .OrderBy(pagination.sidx, pagination.sord)
                        .ToTree();
            /***********************分页处理*********************/
            var rowsData = list.Skip(pagination.pageSize * (pagination.currentPage - 1)).Take(pagination.pageSize);
            pagination.records = list.Count();

            return rowsData;
        }
        /// <summary>
        /// 获取树型列表数据
        /// </summary>
        /// <param name="B_ItemId">字典分类主键</param>
        /// <returns></returns>
        [Caching]
        public virtual List<DataItemDetailEntity> GetDetailTreeList(string B_ItemId)
        {
            var expression = LinqExtensions
                .True<DataItemDetailEntity>()
                .And(c => c.B_EnabledMark == EnabledMark.Enabled);
            if (!B_ItemId.IsEmpty())
            {
                expression = expression.And(c => c.B_ItemId == B_ItemId);
            }
            var list = this.BaseRepository
                .IQueryable(expression)
                .OrderBy(c => c.B_SortCode)
                .ToList();
            list.ForEach(c => c.value = c.B_ItemDetailId);
            return list.ToTree().ToList();
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 保存表头实体(新增,编辑)
        /// </summary>
        /// <param name="formEntity"></param>
        [RemoveCache]
        public virtual (bool, string) SaveHead(DataItemHeadEntity formEntity)
        {
            //字段验重
            if (ValidateHeadExist(formEntity.B_ItemId, "B_ItemName", formEntity.B_ItemName)) return (false, "分类名称已存在！");
            if (ValidateHeadExist(formEntity.B_ItemId, "B_ItemCode", formEntity.B_ItemCode)) return (false, "分类编号已存在！");
            if (!formEntity.B_ItemId.IsEmpty())
            {
                //编辑
                formEntity.Modify();
                this.BaseRepository.Update(formEntity);
            }
            else
            {
                //新增 
                formEntity.Create();
                this.BaseRepository.Insert(formEntity);
            }
            return (true, "保存成功！");
        }
        /// <summary>
        /// 删除表头实体
        /// </summary>
        /// <param name="formEntity"></param>
        [RemoveCache]
        public virtual (bool, string) DeleteHead(DataItemHeadEntity formEntity)
        {
            var db = BaseRepository.BeginTrans();
            try
            {
                //删除表头
                db.Delete(formEntity);
                //删除表体
                db.Delete<DataItemDetailEntity>(c => c.B_ItemId == formEntity.B_ItemId);

                db.Commit();
                return (true, "删除成功！");
            }
            catch (Exception)
            {
                db.Rollback();
                throw;
            }
        }
        /// <summary>
        /// 保存表体实体(新增,编辑)
        /// </summary>
        /// <param name="formEntity"></param>
        [RemoveCache]
        public virtual (bool, string) SaveDetail(DataItemDetailEntity formEntity)
        {
            //字段验重
            if (ValidateDetailExist(formEntity.B_ItemDetailId, "B_ItemName", formEntity.B_ItemName, formEntity.B_ItemId)) return (false, "字典名已存在！");
            if (ValidateDetailExist(formEntity.B_ItemDetailId, "B_ItemValue", formEntity.B_ItemValue, formEntity.B_ItemId)) return (false, "字典值已存在！");
            if (!formEntity.B_ItemDetailId.IsEmpty())
            {
                //编辑
                formEntity.Modify();
                this.BaseRepository.Update(formEntity);
            }
            else
            {
                //新增 
                formEntity.Create();
                this.BaseRepository.Insert(formEntity);
            }
            return (true, "保存成功！");
        }
        /// <summary>
        /// 删除表体实体
        /// </summary>
        /// <param name="formEntity"></param>
        [RemoveCache]
        public virtual (bool, string) DeleteDetail(DataItemDetailEntity formEntity)
        {
            //删除
            this.BaseRepository.Delete(formEntity);
            return (true, "删除成功！");
        }
        /// <summary>
        /// 状态更改
        /// <summary>
        /// <param name="formEntity">数据实体</param>
        /// <returns></returns>
        [RemoveCache]
        public virtual (bool, string) ChangeState(DataItemDetailEntity formEntity)
        {
            if (!formEntity.B_ItemDetailId.IsEmpty())
            {
                this.BaseRepository.Update(new DataItemDetailEntity() { B_ItemDetailId = formEntity.B_ItemDetailId, B_EnabledMark = formEntity.B_EnabledMark });
                this.BaseRepository.Update(formEntity);
                return (true, "更改成功！");
            }
            else
            {
                return (false, "更改失败！");
            }
        }
        #endregion

        #region 数据验证
        /// <summary>
        /// 验证字段值是否存在
        /// </summary>
        /// <param name="id">实体主键</param>
        /// <param name="field">字段名</param>
        /// <param name="value">字段值</param>
        /// <returns></returns>
        public bool ValidateHeadExist(string id, string field, string value)
        {
            var expression = LinqExtensions.True<DataItemHeadEntity>();
            if (!string.IsNullOrEmpty(id))
            {
                expression = expression.And(t => t.B_ItemId != id);
            }
            return this.BaseRepository.IQueryable(expression).Exist(field, value);
        }
        /// <summary>
        /// 验证字段值是否存在
        /// </summary>
        /// <param name="id">实体主键</param>
        /// <param name="field">字段名</param>
        /// <param name="value">字段值</param>
        /// <param name="itemId">分类主键</param>
        /// <returns></returns>
        public bool ValidateDetailExist(string id, string field, string value, string itemId)
        {
            var expression = LinqExtensions.True<DataItemDetailEntity>();
            if (!string.IsNullOrEmpty(id))
            {
                expression = expression.And(t => t.B_ItemDetailId != id);
            }
            if (!string.IsNullOrEmpty(itemId))
            {
                expression = expression.And(t => t.B_ItemId == itemId);
            }
            return this.BaseRepository.IQueryable(expression).Exist(field, value);
        }
        #endregion
    }
}
